<template>
  <div>
    <van-nav-bar title="登录" left-arrow @click-left="$router.back()" />
    <van-form @submit="onSubmit">
      <van-field
        v-model="mobile"
        required
        label="手机号"
        placeholder="请输入手机号"
        :rules="rules.mobile"
      />
      <van-field
        v-model="code"
        required
        label="验证码"
        placeholder="请输入验证码"
        :rules="rules.code"
      />
      <div style="margin: 16px">
        <van-button
          round
          block
          type="info"
          native-type="submit"
          :disabled="isLoading"
          :loading="isLoading"
          loading-text="登录中..."
        >
          提交
        </van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import { userlogin } from '@/api/user'
import { mapMutations } from 'vuex'
export default {
  data() {
    return {
      isLoading: false,
      mobile: '17605656160',
      code: '246810',
      rules: {
        mobile: [
          { required: true, message: '手机号不能为空' },
          {
            pattern: /^1[3-9]\d{9}$/,
            message: '手机号码格式错误'
          }
        ],
        code: [
          { required: true, message: '验证码不能为空' },
          {
            pattern: /^\d{6}$/,
            message: '验证码格式错误'
          }
        ]
      }
    }
  },
  methods: {
    ...mapMutations('user', ['setToken']),
    async onSubmit() {
      this.isLoading = true
      try {
        // const res = await axios({
        //   method: 'POST',
        //   url: '/v1_0/authorizations',
        //   data: {
        //     mobile: this.mobile,
        //     code: this.code
        //   }
        // })
        const res = await userlogin(this.mobile, this.code)
        // console.log(res.data)
        // 保存tokenObj
        // this.$store.commit('user/setToken', res.data)
        // 辅助函数
        this.setToken(res.data)
        // 写死了跳转的页面
        // this.$router.push('/')
        const back = this.$route.query.back || '/user'
        // console.log(back)
        // 如果有flag,使用back进行回退，不要使用push
        const flag = this.$route.query.flag
        if (flag) {
          // 回退
          return this.$router.back()
        }

        this.$router.push(back)

        this.$toast.success('登录成功')
        // this.$router.push('/')
        // alert('登陆成功')
      } catch (e) {
        // alert('登陆失败')
        this.$toast.success('登录失败')
      }
      this.isLoading = false
    }
  }
}
</script>

<style lang="less" scoped></style>
